package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

import com.conversationboard.batch.scheduler.Jobs;
import com.conversationboard.formatter.DateFormatter;
import com.conversationboard.model.User;

@WebServlet(name = "AdminBatchJobStatusControllerServlet", urlPatterns = "/Admin/AdminBatchJobStatusControllerServlet")
public class AdminBatchJobStatusControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -5272230076518887820L;


	private List<Trigger> getTriggers(Scheduler scheduler) throws SchedulerException {

		List<Trigger> triggers = Collections.synchronizedList(new LinkedList<Trigger>());

		String[] triggerGroups = scheduler.getTriggerGroupNames();

		for (String groupName : triggerGroups) {

			if (!groupName.equalsIgnoreCase("DEFAULT")) {
				continue;
			}

			String[] triggersInGroup = scheduler.getTriggerNames(groupName);

			for (String triggerName : triggersInGroup) {
				Trigger trigger = scheduler.getTrigger(triggerName, groupName);
				triggers.add(trigger);
			}

		}

		return triggers;
	}


	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			Scheduler scheduler = Jobs.getScheduler();

			List<JobExecutionContext> currentlyExecutingJobs = (List<JobExecutionContext>) scheduler.getCurrentlyExecutingJobs();
			List<Trigger> triggers = this.getTriggers(scheduler);

			/*
			 * Note that this code assumes there is at least one batch job, or
			 * the loop will throw a NullPointerException
			 */

			Trigger nextTriggerToFire = triggers.get(0);

			for (Trigger trigger : triggers) {
				Date nextFireTime = nextTriggerToFire.getNextFireTime();

				if (trigger.getNextFireTime().before(nextFireTime)) {
					nextTriggerToFire = trigger;
				}
			}

			String prettyFormat = DateFormatter.prettyPrintTime(nextTriggerToFire.getNextFireTime(), user, true, false);

			request.setAttribute("nextTriggerToFire", nextTriggerToFire);
			request.setAttribute("nextTriggerToFirePretty", prettyFormat);
			request.setAttribute("currentServerTime", new Date());
			request.setAttribute("currentlyExecutingJobs", currentlyExecutingJobs);
			request.setAttribute("noJobs", currentlyExecutingJobs.isEmpty());
			request.setAttribute("triggers", triggers);
			request.setAttribute("inStandby", scheduler.isInStandbyMode());

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/view-batch-status.jsp");

			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (SchedulerException e) {
			throw new ServletException(e);
		}

	}

}
